package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pojo.User;
import service.UserService;

import java.util.List;

/**
 * 用户表控制器
 */
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    // 根据ID查询用户
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Integer id) {
        return userService.findUserById(id);
    }

    // 根据用户名查询用户
    @GetMapping("/username/{username}")
    public User getUserByUsername(@PathVariable String username) {
        return userService.findUserByUsername(username);
    }

    // 查询所有用户
    @GetMapping("/all")
    public List<User> getAllUsers() {
        return userService.findAllUsers();
    }

    // 新增用户
    @PostMapping("/add")
    public int addUser(@RequestBody User user) {
        // 确保必要字段不为null
        if (user.getUsername() == null || user.getPassword() == null) {
            throw new IllegalArgumentException("用户名和密码不能为空");
        }
        return userService.addUser(user);
    }

    // 更新用户
    @PutMapping("/update")
    public int updateUser(@RequestBody User user) {
        if (user.getId() == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        return userService.updateUser(user);
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public int deleteUser(@PathVariable Integer id) {
        return userService.deleteUser(id);
    }

    // 锁定/解锁用户
    @PutMapping("/{id}/lock")
    public String lockUser(@PathVariable Integer id, @RequestParam Boolean isLocked) {
        int result = userService.lockUser(id, isLocked);
        return result > 0 ? "操作成功" : "操作失败";
    }
}